﻿//
// Copyright (c) 2024 BPer
//
#include <bperice/BPerRtcSocket.h>
#include <bperrtc/BPerRtcContext.h>

#include <bperssl/BPerSsl.h>
#include <bperssl/BPerRtcDtls.h>

#include <bperstream/BPerStreamType.h>

#include <bperutil/sys/BPerLog.h>
#include <bperutil/sys/BPerSsrc.h>

#if BPer_Enable_Dtls
BPerCertificate* g_bPer_certificate=NULL;
int32_t g_bPer_cerCount=0;
void* bPer_get_global_certificate(){
	if(g_bPer_certificate==NULL){
		g_bPer_certificate = (BPerCertificate*) bPer_calloc(sizeof(BPerCertificate),1);
		bPer_create_certificate(g_bPer_certificate);
	}
	g_bPer_cerCount++;
	return g_bPer_certificate;
}
void bPer_destroy_global_certificate(){
	g_bPer_cerCount--;
	if(g_bPer_cerCount==0){
		bPer_destroy_certificate(g_bPer_certificate);
		bPer_free(g_bPer_certificate);
		g_bPer_destroy_srtp();
	}
}

#endif
bPer_vector_impl(BPerRtcTrack)

void bPer_create_rtcContext(BPerRtcContext *context) {
	if (context == NULL)
		return;
	context->state = BPer_Conn_State_New;
	context->videoCodec = BPer_VED_H264;

	context->audioSsrc = bPer_generate_ssrc();
	context->videoSsrc = bPer_generate_ssrc();

	context->twccId = BPer_TWCC_ID;

	context->sock = ( BPerRtcSocket*) bPer_calloc(sizeof(BPerRtcSocket),1);

	bPer_memset(context->sock, 0, sizeof(BPerRtcSocket));

#if BPer_Enable_Dtls
	bPer_memset(&context->srtp, 0, sizeof(context->srtp));

	context->cer=(BPerCertificate*) bPer_get_global_certificate();

	context->dtls = ( BPerRtcDtls*) bPer_calloc(sizeof(BPerRtcDtls),1);
	context->dtls->session.sock = context->sock;
	context->dtls->session.srtp = &context->srtp;
	context->dtls->session.cer = context->cer;
#endif
	bPer_create_BPerRtcTrackVector(&context->videoTracks);

	bPer_create_bandwidth(&context->bandwidth);
	bPer_create_rtcstats(&context->stats);
#if BPer_Enable_TWCC
	bPer_create_rtctwcc(&context->twcc);
#endif

}

void bPer_destroy_rtcContext(BPerRtcContext *context) {
	if (context == NULL)	return;
	context->streamConfig = NULL;
	bPer_free(context->stun.data);
	if (context->sock&&context->sock->stop&&context->sock->session.isStart)
		context->sock->stop(&context->sock->session);
	bPer_destroy_rtcsocket(context->sock);
	bPer_free(context->sock);
#if BPer_Enable_Dtls
	bPer_destroy_rtcdtls(context->dtls);
	bPer_free(context->dtls);
	bPer_destroy_global_certificate();
#endif
	bPer_destroy_BPerRtcTrackVector(&context->videoTracks);

	bPer_destroy_bandwidth(&context->bandwidth);
	bPer_destroy_rtcstats(&context->stats);
#if BPer_Enable_TWCC
	bPer_destroy_rtctwcc(&context->twcc);
#endif

}

int32_t bPer_has_ssrc(BPerRtcTrack *track, uint32_t ssrc) {
	if (ssrc == track->ssrc || ssrc == track->rtxSsrc
			|| ssrc == track->fecSsrc) {
		return 1;
	}

	return 0;
}

